const fp = require("lodash/fp");
const { MayBe, Container } = require("./support")

/**
 * 代码题一
 */

// 数据
const cars = [
    { name: "cars1", housepower: 660, dollar_value: 700000, in_stock: true },
    { name: "cars2", housepower: 650, dollar_value: 648000, in_stock: false },
    { name: "cars3", housepower: 550, dollar_value: 132000, in_stock: false },
    { name: "cars4", housepower: 525, dollar_value: 114200, in_stock: false },
    { name: "cars5", housepower: 750, dollar_value: 185000, in_stock: true },
    { name: "cars6", housepower: 700, dollar_value: 130000, in_stock: false },
]


// let inLastInStock = function (cars) {
//     let last_car = fp.last(cars)
//     return fp.prop('in_stock', last_car)
// }
// const key = inLastInStock(cars);
// console.log(key)

//练习1
const inLastInStock1 = fp.flowRight(fp.prop('in_stock'), fp.last)
console.log(inLastInStock1(cars))

//练习2
const inLastInStock2 = fp.flowRight(fp.prop('name'), fp.first)
console.log(inLastInStock2(cars))

//练习3
const _average = function (xs) {
    return fp.reduce(fp.add, 0, xs) / xs.length
}
const _map = fp.map(cars => cars.dollar_value)

const inLastInStock3 = fp.flowRight(_average, _map)
console.log(inLastInStock3(cars))

//练习4
const _underscore = fp.replace(/\s+/g, '_')
const sanitizeNames = fp.flowRight(fp.map(fp.flowRight(fp.toLower, _underscore)))
console.log(sanitizeNames(["Hello World"]))

/**
 * 代码题二
 */
//练习1
let maybe = MayBe.of([5, 6, 1])
let ex1 = fp.map(fp.add(2))
console.log(ex1(maybe._value))
//练习2
let xs = Container.of([1, 2, 3, 4, 5, 6, 7])
let ex2 = fp.first
console.log(ex2(xs._value))
//练习3
let safeProp = fp.curry(function (x, o) {
    return MayBe.of(o[x])
})
let user = { id: 2, name: "Albert" }
let ex3 = fp.first(safeProp("name", user)._value)
console.log(ex3)
//练习4
let ex4 = function (n) {
    return parseInt(MayBe.of(n)._value)
}
console.log(ex4("123t"))
